package com.htjc.integral.conversion.inner.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * common xml conver utility
 * 
 * @author viruscodecn@gmail.com
 * @version Framework 2010.10.26
 * @url http://blog.csdn.net/arjick/article/details/6251777
 */
public class XmlConverUtil {
	
	public static void main(String[] args){
		
	String xml = "﻿﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?> <ROOT><ITEM><MSGCODE>0</MSGCODE><MSGDESP>成功接收妥投信息</MSGDESP></ITEM></ROOT>";
	
	if(xml.indexOf("<![CDATA[")>=0){
		xml = StringUtils.replace(xml, "<![CDATA[", "");// result.replaceAll("<![CDATA[", "");
	}
	if(xml.indexOf("]]>")>=0){
		xml = StringUtils.replace(xml, "]]>", "");//result.replaceAll("]]>", "");
	}
	
	String xml2 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><data><CONLISTS><CONLIST><consNo>用电编号</consNo><score>1</score>"
          +" <orgNo>网省代码</orgNo><creatTime>电力积分生成时间</creatTime><id>电力积分生成流水id </id></CONLIST><CONLIST><consNo>用电编号</consNo><score>1</score>"
          +" <orgNo>网省代码</orgNo><creatTime>电力积分生成时间</creatTime><id>电力积分生成流水id </id></CONLIST></CONLISTS></data>";
	
	SAXReader reader =  new SAXReader();//获取读取xml的对象。
	 Document doc;
	try {
		doc = reader.read(new File("D:/1.xml"));
		String xml3 = doc.asXML();
		List<Map<String, Object>> resultMap = XmlConverUtil.ResultXmltoMap2(xml3);
		  System.out.println(resultMap);
	} catch (DocumentException e) {
		e.printStackTrace();
	}
	 
	}
	
	
    public static String xml2JSON(String xml){
        return new XMLSerializer().read(xml).toString();
    }
	
	
	/**
	 * map to xml xml <node><key label="key1">value1</key><key
	 * label="key2">value2</key>......</node>
	 * 
	 * @param map
	 * @return
	 */
	public static String maptoXml(Map map) {
		Document document = DocumentHelper.createDocument();
		Element nodeElement = document.addElement("ROOT");
		for (Object obj : map.keySet()) {
			Element keyElement = nodeElement.addElement(String.valueOf(obj));
			//keyElement.addAttribute("label", String.valueOf(obj));
			keyElement.setText(String.valueOf(map.get(obj)));
		}
		return doc2String(document);
	}
	
	/**
	 * 将请购单转化成XML
	 * 
	 * */
	public static String ListToXml(List<Map<String,Object>> list){
		Document document = DocumentHelper.createDocument();
		Element nodeElement = document.addElement("ROOT");
		
		for(Map<String,Object> map : list){
			Element itemElement = nodeElement.addElement("ITEM");
			for (Object obj : map.keySet()) {
				Element keyElement = itemElement.addElement(String.valueOf(obj));
				//keyElement.addAttribute("label", String.valueOf(obj));
				keyElement.setText(String.valueOf(map.get(obj)));
			}
		}
		return doc2String(document);
	}
	
	/**
	 *将请购单推送到ERP后返回的报文信息转化成map
	 * 
	 * @param xml
	 * @return
	 */
	public static Map ResultXmltoMap(String xml) {
		try {
			 if(xml.indexOf("<") != -1 && xml.lastIndexOf(">") != -1 && xml.lastIndexOf(">") > xml.indexOf("<")){
				 //去除解析内容内包含BOM 
				 xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf(">") + 1);
			 }
			 if(xml.indexOf("xmlversion")>=0){
				 xml = StringUtils.replace(xml, "xmlversion","xml version");
			 }
			 
			Map map = new HashMap();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List nodeitem = nodeElement.elements();
			for (Iterator it = nodeitem.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				List node = elm.elements();
				for (Iterator nodeit = node.iterator(); nodeit.hasNext();){
					Element nodeelm = (Element)  nodeit.next();
					map.put(nodeelm.getName(), nodeelm.getText());
					node = null;
				}
				elm = null;
			}
			nodeitem = null;
			nodeElement = null;
			document = null;
			//处理积分返回结果，去掉小数
			if(map.containsKey("score")){
				String score=String.valueOf(map.get("score"));
				score=score.indexOf(".")>-1?score.substring(0,score.indexOf(".")):score;
				if("".equals(score)||null==score){
					score="0";
				}
				map.put("score",score );
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<Map<String, Object>> ResultXmltoMap2(String xml) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			 if(xml.indexOf("<") != -1 && xml.lastIndexOf(">") != -1 && xml.lastIndexOf(">") > xml.indexOf("<")){
				 //去除解析内容内包含BOM 
				 xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf(">") + 1);
			 }
			 if(xml.indexOf("xmlversion")>=0){
				 xml = StringUtils.replace(xml, "xmlversion","xml version");
			 }
			 
			Map map = new HashMap();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List nodeitem = nodeElement.elements();//consList
			
			for (Iterator it = nodeitem.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				List node = elm.elements();
				for (Iterator nodeit = node.iterator(); nodeit.hasNext();){
					Element nodeeCons = (Element)  nodeit.next();
					
					map.put(nodeeCons.getName(), nodeeCons.getText());
					//处理积分返回结果，去掉小数
					if(map.containsKey("score")){
						String score=String.valueOf(map.get("score"));
						score=score.indexOf(".")>-1?score.substring(0,score.indexOf(".")):score;
						if("".equals(score)||null==score){
							score="0";
						}
						map.put("score",score );
					}					
					node = null;
				}
				list.add(map);
				map = new HashMap();
				elm = null;
			}			
			
			nodeitem = null;
			nodeElement = null;
			document = null;
			
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 *将xml转化成List<Map<String,Object>>
	 * 
	 * @param xml
	 * @return
	 */
	public static List<Map<String,Object>> ResultXmltoListMap(String xml) {
		try {
			List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
			Map map = new HashMap<String, Object>();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List nodeitem = nodeElement.elements();
			for (Iterator it = nodeitem.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				List node = elm.elements();
				for (Iterator nodeit = node.iterator(); nodeit.hasNext();){
					Element nodeelm = (Element)  nodeit.next();
					map.put(nodeelm.getName(), nodeelm.getText());
					nodeelm = null;
					node = null;
				}
				elm = null;
				listMap.add(map);
				map = new HashMap<String, Object>();
			}
			nodeitem = null;
			nodeElement = null;
			document = null;
			return listMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * list to xml xml <nodes><node><key label="key1">value1</key><key
	 * label="key2">value2</key>......</node><node><key
	 * label="key1">value1</key><key
	 * label="key2">value2</key>......</node></nodes>
	 * 
	 * @param list
	 * @return
	 */
	public static String listtoXml(List list) throws Exception {
		Document document = DocumentHelper.createDocument();
		Element nodesElement = document.addElement("nodes");
		int i = 0;
		for (Object o : list) {
			Element nodeElement = nodesElement.addElement("node");
			if (o instanceof Map) {
				for (Object obj : ((Map) o).keySet()) {
					Element keyElement = nodeElement.addElement("key");
					keyElement.addAttribute("label", String.valueOf(obj));
					keyElement.setText(String.valueOf(((Map) o).get(obj)));
				}
			} else {
				Element keyElement = nodeElement.addElement("key");
				keyElement.addAttribute("label", String.valueOf(i));
				keyElement.setText(String.valueOf(o));
			}
			i++;
		}
		return doc2String(document);
	}

	/**
	 * json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver
	 * <o><node class="object"><key class="object"
	 * label="key1">value1</key></node></o>
	 * 
	 * @param json
	 * @return
	 */
	public static String jsontoXml(String json) {
		try {
			XMLSerializer serializer = new XMLSerializer();
			JSON jsonObject = JSONSerializer.toJSON(json);
			return serializer.write(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * xml to map xml <node><key label="key1">value1</key><key
	 * label="key2">value2</key>......</node>
	 * 
	 * @param xml
	 * @return
	 */
	public static Map xmltoMap(String xml) {
		try {
			Map map = new HashMap();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List node = nodeElement.elements();
			for (Iterator it = node.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				map.put(elm.attributeValue("label"), elm.getText());
				elm = null;
			}
			node = null;
			nodeElement = null;
			document = null;
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Map xmltoMap2(String xml) {
		try {
			Map map = new HashMap();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List node = nodeElement.elements();
			for (Iterator it = node.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				map.put(elm.getName(), elm.getText());
				elm = null;
			}
			node = null;
			nodeElement = null;
			document = null;
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * xml to list xml <nodes><node><key label="key1">value1</key><key
	 * label="key2">value2</key>......</node><node><key
	 * label="key1">value1</key><key
	 * label="key2">value2</key>......</node></nodes>
	 * 
	 * @param xml
	 * @return
	 */
	public static List xmltoList(String xml) {
		try {
			List<Map> list = new ArrayList<Map>();
			Document document = DocumentHelper.parseText(xml);
			Element nodesElement = document.getRootElement();
			List nodes = nodesElement.elements();
			for (Iterator its = nodes.iterator(); its.hasNext();) {
				Element nodeElement = (Element) its.next();
				Map map = xmltoMap(nodeElement.asXML());
				list.add(map);
				map = null;
			}
			nodes = null;
			nodesElement = null;
			document = null;
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * xml to json <node><key label="key1">value1</key></node> 转化为
	 * {"key":{"@label":"key1","#text":"value1"}}
	 * 
	 * @param xml
	 * @return
	 */
	public static String xmltoJson(String xml) {
		XMLSerializer xmlSerializer = new XMLSerializer();
		return xmlSerializer.read(xml).toString();
	}

	/**
	 * 
	 * @param document
	 * @return
	 */
	public static String doc2String(Document document) {
		String s = "";
		try {
			// 使用输出流来进行转化
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			// 使用UTF-8编码
			OutputFormat format = new OutputFormat("   ", true, "UTF-8");
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(document);
			s = out.toString("UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return s;
	}
	
	
	public static String getFileTextUtf_8(String filePath) throws IOException{
		FileInputStream fis = new FileInputStream(filePath);
//		byte[] b = IOUtils.toByteArray(fis);
//		BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"GBK"));  
		BufferedReader br = new BufferedReader(new FileReader(filePath));
//		
		StringBuffer buffer = new StringBuffer();
		String temp = null;
		
		while((temp=br.readLine())!=null) {
			buffer.append(new String(temp));
		}
		return  new String(buffer.toString().getBytes(),"utf-8");

	}
	
	public static String zhejiangStrFormat(String resStr){
		if(null!=resStr && !"".equals(resStr)){
			resStr=resStr.replaceAll("\"", "");
			resStr="<consLists><consList>"+resStr;
			if(resStr.indexOf("C N=rtnMsg")>-1){
				resStr=resStr.replace("C N=rtnMsg", "rtnMsg");
				resStr=resStr.replaceFirst("</C>","</rtnMsg>");
			}
			if(resStr.indexOf("C N=id")>-1){
				resStr=resStr.replace("C N=id", "id");
				resStr=resStr.replaceFirst("</C>","</id>");
			}
			if(resStr.indexOf("C N=consNo")>-1){
				resStr=resStr.replace("C N=consNo", "consNo");
				resStr=resStr.replaceFirst("</C>","</consNo>");
			}
			if(resStr.indexOf("C N=consNo")>-1){
				resStr=resStr.replace("C N=consNo", "consNo");
				resStr=resStr.replaceFirst("</C>","</consNo>");
			}
			if(resStr.indexOf("C N=orgNo")>-1){
				resStr=resStr.replace("C N=orgNo", "orgNo");
				resStr=resStr.replaceFirst("</C>","</orgNo>");
			}
			if(resStr.indexOf("C N=rtnCode")>-1){
				resStr=resStr.replace("C N=rtnCode", "rtnCode");
				resStr=resStr.replaceFirst("</C>","</rtnCode>");
			}
			if(resStr.indexOf("C N=score")>-1){
				resStr=resStr.replace("C N=score", "score");
				resStr=resStr.replaceFirst("</C>","</score>");
			}
			if(resStr.indexOf("C N=freezeamt")>-1){
				resStr=resStr.replace("C N=freezeamt", "freezeamt");
				resStr=resStr.replaceFirst("</C>","</freezeamt>");
			}
			
			resStr=resStr+"</consList></consLists>";
		}
		return resStr;
	}
}
